package com.hz.friends.chat;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import org.json.JSONObject;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.callback.BitmapAjaxCallback;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVUser;
import com.hisun.phone.core.voice.Device;
import com.hisun.phone.core.voice.model.im.IMTextMsg;
import com.hisun.phone.core.voice.model.im.InstanceMsg;
import com.hz.friends.activity.BigImageActivity;
import com.hz.friends.activity.R;
import com.hz.friends.activity.UserInfosActivity;
import com.hz.friends.application.CustomApplication;
import com.hz.friends.chat.Helper.CCPHelper;
import com.hz.friends.chat.entity.IMChatMessage;
import com.hz.friends.db.DBContactUser;
import com.hz.friends.db.DBMessageManager;
import com.hz.friends.global.Global;
import com.hz.friends.serverrequest.ALCCPEngine;
import com.hz.friends.serverrequest.ALCCPEngine.ALGroupType;
import com.hz.friends.serverrequest.ALCCPEngine.ALMessageOfChatType;
import com.hz.friends.serverrequest.ALEngineConfig.CallBack;
import com.hz.friends.utils.BitmapUtils;
import com.hz.friends.utils.DensityUtil;
import com.hz.friends.utils.MLog;
import com.hz.friends.utils.UtilTools;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.Spannable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.BufferType;

public class MessageAdpter extends BaseAdapter {
	private List<IMChatMessage> data = new ArrayList<IMChatMessage>();
	private Context context = null;
	private LayoutInflater inflater = null;
	private AQuery aq;
	private MediaPlayer mMediaPlayer = new MediaPlayer();
	private ImageView palyingImageView = null;
	private int lastimstate = IMChatMessage.MessageDirect.SENT;
	private final String TAG = this.getClass().getSimpleName();
	private String toVoip = "80609900000002";
	private DBMessageManager dbmanager = null;
	private int longclickindex = -1;
    
	public int getLongclickindex() {
		return longclickindex;
	}

	public void setLongclickindex(int longclickindex) {
		this.longclickindex = longclickindex;
	}

	public void setToVoip(String tovoip) {
		this.toVoip = tovoip;
	}

	@Override
	public int getCount() {
		return data.size();
	}

	public MessageAdpter(Context context) {
		this.context = context;
		inflater = LayoutInflater.from(context);
		aq = new AQuery(context);
		dbmanager = new DBMessageManager(context);
		CCPHelper.getInstance().setHandler(mhandler);

	}

	@Override
	public IMChatMessage getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	public void getFirstData(String fromuserid) {
		List<IMChatMessage> firstmessages = dbmanager
				.queryMessagesFirstdiplayByFromUserId(fromuserid);
		if (firstmessages != null && firstmessages.size() > 0) {
			addData(firstmessages);
			this.notifyDataSetChanged();
		}
	}

	/**
	 * 查询用户单聊历史记录
	 * 
	 * @param userId
	 * @param pageindex
	 */
	public int getBeforeMessages(String userId, int pageindex) {
		if (pageindex == 0)
			this.data.clear();
		List<IMChatMessage> messages = dbmanager.queryMessagesByFromUserId(
				userId, pageindex);
		addData(messages);
		this.notifyDataSetChanged();
		return messages == null ? 0 :messages.size();
	}

	public void addData(List<IMChatMessage> data) {
		if (data == null)
			return;
		this.data.addAll(data);
		sortData();
	}

	public void addData(IMChatMessage immsg) {
		this.data.add(immsg);
		sortData();
	}

	// 以时间递增排序
	public void sortData() {
		Collections.sort(data, new Comparator<IMChatMessage>() {
			@Override
			public int compare(IMChatMessage msg1, IMChatMessage msg2) {
				if (msg1.getMessagetime().before(msg2.getMessagetime())){
					return -1;
				}else if (msg1.getMessagetime().after(msg2.getMessagetime())) {
					return  1;
				}else{
					return 0;
				}
			}
		});
	}

	// public void addTopDat(IMChatMessage immsg){
	// this.data.addFirst(immsg);
	// }

	// public void addTopDat(List<IMChatMessage> data){
	// for (int i = 0; i < data.size(); i++) {
	// this.data.add(data.get(i));
	// }
	//
	// }

	public void clearData() {
		this.data.clear();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final IMChatMessage message = data.get(position);
		convertView = null;
		final ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = createViewByMessage(message);
			try {
				if (message.getMessageType() == IMChatMessage.MessageType.TXT) {
					holder.imv_heard = (ImageView) convertView
							.findViewById(R.id.imv_heard);
					holder.txv_content = (TextView) convertView
							.findViewById(R.id.txv_content);
					holder.txv_content_tran = (TextView) convertView
							.findViewById(R.id.txv_trancontent);
					holder.txv_time = (TextView) convertView
							.findViewById(R.id.txv_time);
					holder.txv_trantips = (TextView) convertView
							.findViewById(R.id.txv_trantips);
					holder.view_divier = convertView
							.findViewById(R.id.view_divier);
					holder.progressbar = (ProgressBar) convertView
							.findViewById(R.id.progressBar);
					holder.imv_sendfail = (ImageView) convertView
							.findViewById(R.id.imv_sendfail);
				} else if (message.getMessageType() == IMChatMessage.MessageType.VOICE) {
					holder.imv_heard = (ImageView) convertView
							.findViewById(R.id.imv_heard);
					holder.txv_time = (TextView) convertView
							.findViewById(R.id.txv_time);
					holder.txv_voiceduration = (TextView) convertView
							.findViewById(R.id.txv_voiceduration);
					holder.imv_pic = (ImageView) convertView
							.findViewById(R.id.imv_pic);
					holder.progressbar = (ProgressBar) convertView
							.findViewById(R.id.progressBar);
					holder.imv_sendfail = (ImageView) convertView
							.findViewById(R.id.imv_sendfail);
					holder.layout_voice = (FrameLayout)convertView.findViewById(R.id.layout_voice);

				} else if (message.getMessageType() == IMChatMessage.MessageType.IMAGE) {
					holder.imv_heard = (ImageView) convertView
							.findViewById(R.id.imv_heard);
					holder.txv_time = (TextView) convertView
							.findViewById(R.id.txv_time);
					holder.imv_pic = (ImageView) convertView
							.findViewById(R.id.imv_pic);
					holder.progressbar = (ProgressBar) convertView
							.findViewById(R.id.progressBar);
					holder.imv_sendfail = (ImageView) convertView
							.findViewById(R.id.imv_sendfail);
				} else  if (message.getMessageType() == IMChatMessage.MessageType.VIDEO){
					holder.imv_heard = (ImageView) convertView
							.findViewById(R.id.imv_heard);
					holder.txv_time = (TextView) convertView
							.findViewById(R.id.txv_time);
					holder.imv_pic = (ImageView) convertView
							.findViewById(R.id.imv_pic);
					holder.progressbar = (ProgressBar) convertView
							.findViewById(R.id.progressBar);
					holder.imv_sendfail = (ImageView) convertView
							.findViewById(R.id.imv_sendfail);

				}else{
					holder.imv_heard = (ImageView) convertView
							.findViewById(R.id.imv_heard);
					holder.txv_content = (TextView) convertView
							.findViewById(R.id.txv_content);
					holder.txv_content_tran = (TextView) convertView
							.findViewById(R.id.txv_trancontent);
					holder.txv_time = (TextView) convertView
							.findViewById(R.id.txv_time);
					holder.txv_trantips = (TextView) convertView
							.findViewById(R.id.txv_trantips);
					holder.view_divier = convertView
							.findViewById(R.id.view_divier);
					holder.progressbar = (ProgressBar) convertView
							.findViewById(R.id.progressBar);
					holder.imv_sendfail = (ImageView) convertView
							.findViewById(R.id.imv_sendfail);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}

		// 填充数据
		initViewByMessage(message, holder, position);
		return convertView;
	}

	private View createViewByMessage(IMChatMessage message) {
		switch (message.getMessageType()) {
		case IMChatMessage.MessageType.TXT:
			return message.getMessageDirection() == IMChatMessage.MessageDirect.RECEIVE ? inflater
					.inflate(R.layout.row_receive_message, null) : inflater
					.inflate(R.layout.row_sent_message, null);

		case IMChatMessage.MessageType.VOICE:
			return message.getMessageDirection() == IMChatMessage.MessageDirect.RECEIVE ? inflater
					.inflate(R.layout.row_recevie_voice, null) : inflater
					.inflate(R.layout.row_sent_voice, null);

		case IMChatMessage.MessageType.IMAGE:
			return message.getMessageDirection() == IMChatMessage.MessageDirect.RECEIVE ? inflater
					.inflate(R.layout.row_recevie_pic, null) : inflater
					.inflate(R.layout.row_sent_pic, null);

		case IMChatMessage.MessageType.VIDEO:
			return message.getMessageDirection() == IMChatMessage.MessageDirect.RECEIVE ? inflater
					.inflate(R.layout.row_recevie_video, null) : inflater
					.inflate(R.layout.row_sent_video, null);
		default:
			return message.getMessageDirection() == IMChatMessage.MessageDirect.RECEIVE ? inflater
					.inflate(R.layout.row_receive_message, null) : inflater
					.inflate(R.layout.row_sent_message, null);
		}

	}

	private void initViewByMessage(final IMChatMessage message,
			final ViewHolder holder, final int postion) {
		// 时间标签
		Date time = message.getMessagetime();
		if (postion - 1 > -1) {
			Date lasttime = data.get(postion - 1).getMessagetime(); // 上一条消息时间
			if (time != null && lasttime != null
					&& time.getTime() - lasttime.getTime() > 3 * 60 * 1000) {// 3分钟间隔
				SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
				holder.txv_time.setVisibility(View.VISIBLE);
				holder.txv_time.setText(sdf.format(time));
			} else {
				holder.txv_time.setVisibility(View.GONE);
			}
		}
		// 头像
		DBContactUser avuser =message.getMessageDirection() == IMChatMessage.MessageDirect.SENT ?new DBContactUser(AVUser.getCurrentUser()):message.getFromuser();
		if (avuser != null) {
			String heardurl = avuser.getHeardurl();
			// aq.id(holder.imv_heard).image(heardurl, true, true);

			// default image
			final int width = DensityUtil.dip2px(context, 40);
			Bitmap crclebitmap = BitmapUtils.drawCycleImage("#c4c4c5", width);
			Bitmap crclestrokebitmap = BitmapUtils.getCircleStrokbitmap(
					context, crclebitmap, width, 1, "#eeeeee");
			holder.imv_heard.setImageBitmap(crclestrokebitmap);

			aq.id(holder.imv_heard).image(heardurl, true, true, width, 0,
					new BitmapAjaxCallback() {
						@Override
						protected void callback(String url, ImageView iv,
								Bitmap bm, AjaxStatus status) {
							super.callback(url, iv, bm, status);
							Bitmap mbitmap = BitmapUtils.getCircleStrokbitmap(
									context, bm, width, 1, "#eeeeee");
							holder.imv_heard.setImageBitmap(mbitmap);
						}
					});
		}

		// 消息状态处理
		int imstate = message.getImState();
		if (message.getMessageDirection() == IMChatMessage.MessageDirect.SENT) {
			if (imstate == IMChatMessage.STATE_IM_SEND_FAILED) {// 发送失败
				holder.imv_sendfail.setVisibility(View.VISIBLE);
				holder.progressbar.setVisibility(View.GONE);
			} else if (imstate == IMChatMessage.STATE_IM_SEND_SUCCESS) {// 发送成功
				holder.progressbar.setVisibility(View.GONE);
				holder.imv_sendfail.setVisibility(View.GONE);
			} else if (imstate == IMChatMessage.STATE_IM_SENDING) {// 发送中
				holder.imv_sendfail.setVisibility(View.GONE);
				holder.progressbar.setVisibility(View.VISIBLE);
			} else {
				holder.progressbar.setVisibility(View.GONE);
				holder.imv_sendfail.setVisibility(View.GONE);
			}
		}

		final String mediaurl = message.getMediaUrl();
		final String mediapath = message.getMediaPath();

		switch (message.getMessageType()) {
		case IMChatMessage.MessageType.TXT:
			Spannable span = SmileUtils.getSmiledText(context,
					message.getMessageContent());
			holder.txv_content.setText(span, BufferType.SPANNABLE);
			if(message.isTranflag()){
				holder.txv_content_tran.setText(span, BufferType.SPANNABLE);
				holder.txv_content_tran.setVisibility(View.VISIBLE);
				holder.txv_trantips.setVisibility(View.VISIBLE);
				holder.view_divier.setVisibility(View.VISIBLE);
			}else{
				holder.txv_content_tran.setVisibility(View.GONE);
				holder.txv_trantips.setVisibility(View.GONE);
				holder.view_divier.setVisibility(View.GONE);
			}

			break;
		case IMChatMessage.MessageType.VOICE:
			long duration = message.getMediaduration();
			final String voicepath = message.getMediaPath();
			holder.txv_voiceduration.setText(duration + "\'\'");
			holder.layout_voice.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					String url = null;
					if (voicepath != null)
						url = voicepath;
					else
						url = mediaurl;
					playMusic(url, holder.imv_pic,
							message.getMessageDirection());
				}
			});
			
			holder.layout_voice.setOnLongClickListener(new OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
//					setLongclickindex(postion);
//					((GroupChatActivity)context).showContextMenu(postion);
 					return false;
				}
			});

			break;
		case IMChatMessage.MessageType.IMAGE:
			// aq.id(holder.imv_pic).image(message.getImageThumb());
			// 重新设置图片view宽高
			int imagewidth = message.getImageWidth();
			int imageheight = message.getImageHeight();
			int imageViewWidth = DensityUtil.dip2px(context, 100);
			int imageViewHeight = (int) (((imageViewWidth * 1.0f) / imagewidth) * imageheight);
			FrameLayout.LayoutParams imagelap = new FrameLayout.LayoutParams(
					imageViewWidth, imageViewHeight);
			holder.imv_pic.setLayoutParams(imagelap);
			String imageurl = mediapath == null ? mediaurl + "?smallpic"
					: mediapath;
			aq.id(holder.imv_pic).progress(holder.progressbar)
					.image(imageurl, true, true, imageViewWidth, 0);
			// 查看大图
			holder.imv_pic.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent largeintent = new Intent(context,
							BigImageActivity.class);
					if (mediapath != null) {
						largeintent.putExtra("imagePath", mediapath);
					} else {
						largeintent.putExtra("imageUrl", mediaurl);
					}
					context.startActivity(largeintent);
				}
			});
			holder.imv_pic.setOnLongClickListener(new OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
//					setLongclickindex(postion);
//					((GroupChatActivity)context).showContextMenu(postion);
 					return false;
				}
			});

			break;
		case IMChatMessage.MessageType.VIDEO:
			// aq.id(holder.imv_pic).image(message.getImageThumb());
			holder.imv_pic.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					Uri uri = null;
					if(mediaurl != null)
					   uri = Uri.parse(mediaurl);
					if(mediapath != null)
						uri = Uri.parse(mediapath);
					// 调用系统自带的播放器
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(uri, "video/mp4");
					context.startActivity(intent);
				}
			});

			holder.imv_pic.setOnLongClickListener(new OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
//					setLongclickindex(postion);
//					((GroupChatActivity)context).showContextMenu(postion);
 					return false;
				}
			});
			break;
		case IMChatMessage.MessageType.GROUPINVITE://群邀请
			holder.txv_content.setText(message.getMessageContent());
			holder.txv_content.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					setLongclickindex(postion);
					((GroupChatActivity)context).showContextMenu(postion);
				}
			});
			holder.txv_content.setOnLongClickListener(new OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
					return false;
				}
			});
			break;
		default:
			break;
		}
	}

	private static class ViewHolder {
		ProgressBar progressbar; // 等待提示
		TextView txv_time; // 消息时间
		TextView txv_trantips; // 文本已翻译提示
		ImageView imv_heard; // 头像
		ImageView imv_pic; // 图片
		TextView txv_content; // 文本
		TextView txv_content_tran; // 翻译后的文本
		View view_divier; // 文本与翻译直接分割线
		TextView txv_voiceduration; // 语音时长
		ImageView imv_sendfail; // 发送失败提示
		FrameLayout layout_voice; //voice点击区域
	}

	/**
	 * @Description
	 * @param name
	 */
	private void playMusic(final String name, final ImageView iv_voice,
			final int imstate) {
		try {
			synchronized (mMediaPlayer) {// 清除上条消息的状态
				if (mMediaPlayer.isPlaying()) {
					mMediaPlayer.stop();
					if (palyingImageView != null) {
						AnimationDrawable lastvoiceAnimation = (AnimationDrawable) palyingImageView
								.getDrawable();
						if (lastvoiceAnimation != null)
							lastvoiceAnimation.stop();
						if (lastimstate == IMChatMessage.MessageDirect.SENT)
							palyingImageView
									.setImageResource(R.drawable.chatto_voice_playing);
						else
							palyingImageView
									.setImageResource(R.drawable.chatfrom_voice_playing);
					}
				}
			}

			if (imstate == IMChatMessage.MessageDirect.SENT)
				iv_voice.setImageResource(R.anim.voice_to_icon);
			else
				iv_voice.setImageResource(R.anim.voice_from_icon);
			final AnimationDrawable voiceAnimation = (AnimationDrawable) iv_voice
					.getDrawable();
			mMediaPlayer.reset();
			mMediaPlayer.setDataSource(name);
			mMediaPlayer.prepare();
			mMediaPlayer.start();
			voiceAnimation.start();
			palyingImageView = iv_voice;
			lastimstate = imstate;
			mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
				public void onCompletion(MediaPlayer mp) {
					voiceAnimation.stop();
					if (imstate == IMChatMessage.MessageDirect.SENT)
						iv_voice.setImageResource(R.drawable.chatto_voice_playing);
					else
						iv_voice.setImageResource(R.drawable.chatfrom_voice_playing);

				}
			});

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 发送文本消息
	 * 
	 * @param txt
	 * @param toobj
	 *            发送对象user or group
	 */
	public void sendMessage(String txt, AVObject toobj) {

		com.hisun.phone.core.voice.Device d = CCPHelper.getInstance()
				.getDevice();
		if (d == null) {
			MLog.e(TAG, "发送消息device is null!");
			return;
		}

		// String uniqueID = d.sendInstanceMessage(toVoip, txt, null, null);
		// MLog.i(TAG, "[sendMessage] message id "+uniqueID);

		// 添加数据
		final IMChatMessage immsg = new IMChatMessage();
		immsg.setMessageContent(txt);
		immsg.setMessageDirection(IMChatMessage.MessageDirect.SENT);
		immsg.setMessageType(IMChatMessage.MessageType.TXT);
		immsg.setMessagetime(new Date());
		immsg.setIsRead(IMChatMessage.STATE_READED);
		if ("_User".equals(toobj.getClassName())) {
			immsg.setFromuser(new DBContactUser((AVUser) toobj, txt,immsg.getMessagetime()));
		}
		immsg.setMessageId(System.currentTimeMillis() + "");
		this.addData(immsg);
		this.notifyDataSetChanged();
		// if(TextUtils.isEmpty(uniqueID)) {//发送失败
		// Toast.makeText(context, "发送失败", Toast.LENGTH_SHORT).show();
		// immsg.setImState(IMChatMessage.STATE_IM_SEND_FAILED);
		// this.notifyDataSetChanged();
		// return ;
		// }

		ALCCPEngine.defauleEngine().postMessageOfText(txt, toobj,
				new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "sendMessage==object:" + object
								+ "  avexception:" + avexception);
						if (avexception == null) {
							MLog.i(TAG, "sendMessage==success");
							updateMessage(immsg,
									IMChatMessage.STATE_IM_SEND_SUCCESS);
						} else {
							updateMessage(immsg,
									IMChatMessage.STATE_IM_SEND_FAILED);
							MLog.i(TAG, "sendMessage==error");
							avexception.printStackTrace();
						}
						try {
							dbmanager.updateMessageReadState(immsg.getMessageId(),
									immsg.getIsRead(),immsg.getImState());
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});
		if ("_User".equals(toobj.getClassName())) {
			dbmanager.save(immsg);
			dbmanager.saveOrUpdate(immsg.getFromuser());
		}

	}

	/**
	 * 发送语音消息
	 * 
	 * @param voicepath
	 *            语音本地路径
	 * @param duration
	 *            语音时长
	 * @param touser
	 *            接受者 group or user
	 */
	public void sendVoiceMessage(String voicepath, int duration, AVObject touser) {

		com.hisun.phone.core.voice.Device d = CCPHelper.getInstance()
				.getDevice();
		if (d == null) {
			MLog.e(TAG, "发送消息device is null!");
			return;
		}

		// 添加数据
		final IMChatMessage immsg = new IMChatMessage();
		immsg.setMediaPath(voicepath);
		immsg.setMessageDirection(IMChatMessage.MessageDirect.SENT);
		immsg.setMessageType(IMChatMessage.MessageType.VOICE);
		immsg.setMessagetime(new Date());
		immsg.setIsRead(IMChatMessage.STATE_READED);
		if ("_User".equals(touser.getClassName())) {
			immsg.setFromuser(new DBContactUser((AVUser)touser, "[语音]", immsg.getMessagetime()));
		}
		immsg.setMessageId(System.currentTimeMillis() + "");
		immsg.setMediaduration(duration);
		this.addData(immsg);
		this.notifyDataSetChanged();

		ALCCPEngine.defauleEngine().postMessageOfVoicePath(voicepath, duration,
				touser, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "sendVoiceMessage==object:" + object
								+ "  avexception:" + avexception);
						if (avexception == null) {
							updateMessage(immsg,
									IMChatMessage.STATE_IM_SEND_SUCCESS);
						} else {
							updateMessage(immsg,
									IMChatMessage.STATE_IM_SEND_FAILED);
							avexception.printStackTrace();
						}
						try {
							dbmanager.updateMessageReadState(immsg.getMessageId(),
									immsg.getIsRead(),immsg.getImState());
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});
		if ("_User".equals(touser.getClassName())) {
			dbmanager.save(immsg);
			dbmanager.saveOrUpdate(immsg.getFromuser());
		}

	}

	/**
	 * 发送视频消息
	 * 
	 * @param voidepath
	 *            视频本地路径
	 * @param duration
	 *            时长
	 * @param thumbimg
	 *            视频缩略图
	 * @param touser
	 *            接受者 group or user
	 */
	public void sendViodeMessage(String voidepath, int duration,
			Bitmap thumbimg, AVObject touser) {

		com.hisun.phone.core.voice.Device d = CCPHelper.getInstance()
				.getDevice();
		if (d == null) {
			MLog.e(TAG, "发送消息device is null!");
			return;
		}

		// 添加数据
		final IMChatMessage immsg = new IMChatMessage();
		immsg.setMediaPath(voidepath);
		immsg.setMediaduration(duration);
		immsg.setMessageDirection(IMChatMessage.MessageDirect.SENT);
		immsg.setMessageType(IMChatMessage.MessageType.VIDEO);
		immsg.setMessagetime(new Date());
		immsg.setIsRead(IMChatMessage.STATE_READED);
		if ("_User".equals(touser.getClassName())) {
			immsg.setFromuser(new DBContactUser((AVUser)touser, "[视频]", immsg.getMessagetime()));
		}
		immsg.setMessageId(System.currentTimeMillis() + "");
		this.addData(immsg);
		this.notifyDataSetChanged();
		ALCCPEngine.defauleEngine().postMessageOfVideoPath(voidepath, duration,
				touser, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "sendViodeMessage==object:" + object
								+ "  avexception:" + avexception);
						if (avexception == null) {
							updateMessage(immsg,
									IMChatMessage.STATE_IM_SEND_SUCCESS);
						} else {
							updateMessage(immsg,
									IMChatMessage.STATE_IM_SEND_FAILED);
							avexception.printStackTrace();
						}
						try {
							dbmanager.updateMessageReadState(immsg.getMessageId(),
									immsg.getIsRead(),immsg.getImState());
						} catch (Exception e) {
							// TODO: handle exception
						}
					
					}
				});
		if ("_User".equals(touser.getClassName())) {
			dbmanager.save(immsg);
			dbmanager.saveOrUpdate(immsg.getFromuser());
		}
	
	}

	/**
	 * 发送图片消息
	 * 
	 * @param photopath
	 *            图片本地路径
	 * @param thumbImage
	 *            图片缩略图
	 * @param touser
	 *            消息接受者 user or group
	 */
	public void sendPhotoMessage(String photopath, Bitmap thumbImage,
			AVObject touser) {

		com.hisun.phone.core.voice.Device d = CCPHelper.getInstance()
				.getDevice();
		if (d == null) {
			MLog.e(TAG, "发送消息device is null!");
			return;
		}
		// 获取图片宽高
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(photopath, options);

		// 添加数据
		final IMChatMessage immsg = new IMChatMessage();
		immsg.setMediaPath(photopath);
		immsg.setMessageDirection(IMChatMessage.MessageDirect.SENT);
		immsg.setMessageType(IMChatMessage.MessageType.IMAGE);
		immsg.setMessagetime(new Date());
		immsg.setIsRead(IMChatMessage.STATE_READED);
		if ("_User".equals(touser.getClassName())) {
			immsg.setFromuser(new DBContactUser((AVUser)touser, "图片",immsg.getMessagetime()));
		}
		immsg.setMessageId(System.currentTimeMillis() + "");
		immsg.setImageHeight(options.outHeight);
		immsg.setImageWidth(options.outWidth);
		this.addData(immsg);
		this.notifyDataSetChanged();

		ALCCPEngine.defauleEngine().postMessageOfImagePath(photopath,
				options.outWidth, options.outHeight, touser, new CallBack() {

					@Override
					public void done(Object object, AVException avexception) {
						MLog.i(TAG, "sendPhotoMessage==object:" + object
								+ "  avexception:" + avexception);
						if (avexception == null) {
							updateMessage(immsg,
									IMChatMessage.STATE_IM_SEND_SUCCESS);
						} else {
							updateMessage(immsg,
									IMChatMessage.STATE_IM_SEND_FAILED);
							avexception.printStackTrace();
						}

					}
				});
		if ("_User".equals(touser.getClassName())) {
			dbmanager.save(immsg);
			dbmanager.saveOrUpdate(immsg.getFromuser());
		}
		
	}

	public void reciveMessage(AVObject msgofchat) {
		try {
			String objid = msgofchat.getObjectId();
			JSONObject datajson = msgofchat.getJSONObject("userData");
			AVUser fromuser = msgofchat.getAVUser("fromUser");
			int type = datajson.getInt("type");
			String url = datajson.getString("url");

			if (type == ALMessageOfChatType.ALMessageOfChatTypeOfText
					.get_value()) {// 文本
				// 添加数据
				IMChatMessage immsg = new IMChatMessage();
				immsg.setMessageContent(url);
				immsg.setMessageDirection(IMChatMessage.MessageDirect.RECEIVE);
				immsg.setMessageType(IMChatMessage.MessageType.TXT);
				immsg.setMessagetime(msgofchat.getCreatedAt());
				immsg.setMessageId(objid);
				immsg.setFromuser(new DBContactUser(fromuser));
				this.addData(immsg);
				this.notifyDataSetChanged();

			} else if (type == ALMessageOfChatType.ALMessageOfChatTypeOfVoice // 语音
					.get_value()) {
				int voiceduration = datajson.getInt("duration");
				final IMChatMessage immsg = new IMChatMessage();
				immsg.setMessageDirection(IMChatMessage.MessageDirect.RECEIVE);
				immsg.setMessageType(IMChatMessage.MessageType.VOICE);
				immsg.setMessagetime(msgofchat.getCreatedAt());
				immsg.setMessageId(objid);
				immsg.setFromuser(new DBContactUser(fromuser));
				immsg.setMediaUrl(url);
				immsg.setMediaduration(voiceduration);
				this.addData(immsg);
				this.notifyDataSetChanged();
				// 下载文件
				String voicename = url.substring(url.lastIndexOf("/" + 1),
						url.length());
				final String voicefilepath = Environment
						.getExternalStorageDirectory()
						+ "/"
						+ Global.productName + "/voice/" + voicename;
				File voicefile = UtilTools.createFile(voicefilepath);
				if (voicefile != null) {// 文件存在
					if (voicefile.length() > 0) { // 文件包含内容
						immsg.setMediaPath(voicefilepath);
					} else {// 文件不包含内容
						aq.download(url, voicefile, new AjaxCallback<File>() {
							@Override
							public void callback(String url, File object,
									AjaxStatus status) {
								super.callback(url, object, status);
								if (object != null)
									immsg.setMediaPath(voicefilepath);

							}
						});
					}
				}

			} else if (type == ALMessageOfChatType.ALMessageOfChatTypeOfImage// 图片
					.get_value()) {
				IMChatMessage immsg = new IMChatMessage();
				// 设置宽高
				String imagesizes = datajson.getString("size");
				if (!TextUtils.isEmpty(imagesizes) && imagesizes.length() > 2) {
					String[] sizesarr = imagesizes.substring(1,
							imagesizes.length() - 1).split(",");
					if (sizesarr != null && sizesarr.length == 2) {
						immsg.setImageWidth(Integer.parseInt(sizesarr[0]));
						immsg.setImageHeight(Integer.parseInt(sizesarr[1]));
					}
				}

				immsg.setMessageDirection(IMChatMessage.MessageDirect.RECEIVE);
				immsg.setMessageType(IMChatMessage.MessageType.IMAGE);
				immsg.setMessagetime(new Date());
				immsg.setMessageId(objid);
				immsg.setFromuser(new DBContactUser(fromuser));
				immsg.setMediaUrl(url);
				this.addData(immsg);
				this.notifyDataSetChanged();
			} else if (type == ALMessageOfChatType.ALMessageOfChatTypeOfVideo // 视频
					.get_value()) {
				final IMChatMessage immsg = new IMChatMessage();
				immsg.setMessageDirection(IMChatMessage.MessageDirect.RECEIVE);
				immsg.setMessageType(IMChatMessage.MessageType.VIDEO);
				immsg.setMessagetime(msgofchat.getCreatedAt());
				immsg.setMessageId(objid);
				immsg.setFromuser(new DBContactUser(fromuser));
				immsg.setMediaUrl(url);
				this.addData(immsg);
				this.notifyDataSetChanged();

				// //下载文件
				// aq.download(url, null, new AjaxCallback<File>(){
				// public void callback(String url, File object,
				// com.androidquery.callback.AjaxStatus status) {
				// try {
				// String targetdir =
				// Environment.getExternalStorageDirectory()+"/"+Global.productName+"/voide/";
				// String targetpath = targetdir+
				// +System.currentTimeMillis()+".mp4";
				// if(!new File(targetdir).exists())
				// new File(targetdir).mkdirs();
				// File targetfile = new File(targetpath);
				// if(!targetfile.exists())
				// targetfile.createNewFile();
				// UtilTools.copyFile(object, targetfile);
				// immsg.setVoidepath(targetpath);
				// } catch (Exception e) {
				// e.printStackTrace();
				// }
				//
				// };
				// });
			} else {

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		// //添加数据
		// IMChatMessage immsg = new IMChatMessage();
		// immsg.setMessageContent("收到:"+msgofchat.getMessage());
		// immsg.setMessageDirection(IMChatMessage.MessageDirect.RECEIVE);
		// immsg.setMessageType(IMChatMessage.MessageType.TXT);
		// immsg.setMessagetime(new Date());
		// immsg.setMessageId(imtextmsg.getMsgId());
		// immsg.setUser(AVUser.getCurrentUser());
		// this.addData(immsg);
		// this.notifyDataSetChanged();
	}

	private Handler mhandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Bundle bundle = (Bundle) msg.obj;
			// 处理消息发送状态回调
			if (bundle != null) {
				InstanceMsg msgdata = (InstanceMsg) bundle
						.getSerializable(Device.MEDIA_MESSAGE);
				if (msgdata != null && msgdata instanceof IMTextMsg) {
					int reason = bundle.getInt(Device.REASON);
					int msgType = bundle.getInt("msgType");
					switch (msgType) {
					case IMChatMessage.STATE_IM_SEND_SUCCESS: // 发送成功
						updateMessage(((IMTextMsg) msgdata).getMsgId(),
								IMChatMessage.STATE_IM_SEND_SUCCESS);
						break;
					case IMChatMessage.STATE_IM_SEND_FAILED: // 发送失败
						updateMessage(((IMTextMsg) msgdata).getMsgId(),
								IMChatMessage.STATE_IM_SEND_FAILED);
						break;
					default:
						break;
					}

				}

			}
		};
	};

	/**
	 * 更新消息状态
	 * 
	 * @param messageid
	 *            消息id
	 * @param msgstate
	 *            发送成功或发生失败
	 */
	private void updateMessage(String messageid, int msgstate) {
		for (int i = 0; i < this.data.size(); i++) {
			IMChatMessage item = data.get(i);
			String itemmsgid = item.getMessageId();
			if (itemmsgid.equals(messageid)) {
				item.setImState(msgstate);
				this.notifyDataSetChanged();
				return;
			}
		}
	}

	private void updateMessage(final IMChatMessage chatmsg, final int msgstate) {
		chatmsg.setImState(msgstate);
		((Activity) context).runOnUiThread(new Runnable() {

			@Override
			public void run() {
				MessageAdpter.this.notifyDataSetChanged();
			}
		});

	}

	// 退出聊天界面 更新所有消息为已读
	public void updateAllMessageDBToRead() {
		if (data == null || data.size() == 0)
			return;
		for (int i = 0; i < data.size(); i++) {
			IMChatMessage message = data.get(i);
			DBContactUser fromuser = message.getFromuser();
			int imstate = message.getImState();
			if(imstate != IMChatMessage.STATE_IM_SEND_SUCCESS)
				imstate = IMChatMessage.STATE_IM_SEND_FAILED;
			dbmanager.updateMessageReadState(message.getMessageId(),
					IMChatMessage.STATE_READED,imstate);
			if (i == data.size() - 1)
				dbmanager.saveOrUpdate(fromuser);
		}
//		dbmanager.closeDB();
	}

}
